<template>
  <div class="user-center">
    <!-- 导航栏 -->
    <el-menu
      :default-active="activeIndex"
      class="nav-menu"
      mode="horizontal"
      @select="handleSelect"
      background-color="rgba(255, 255, 255, 0.95)"
      text-color="#2c3e50"
      active-text-color="#667eea">
      <el-menu-item index="1">
        <el-icon><User /></el-icon>
        <span>用户管理</span>
      </el-menu-item>
      <el-menu-item index="2">
        <el-icon><Setting /></el-icon>
        <span>系统设置</span>
      </el-menu-item>

      <!-- 搜索框 -->
      <div class="nav-search">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名或邮箱"
          class="nav-search-input"
          @keyup.enter="handleSearch">
          <template v-slot:prefix>
            <el-icon class="search-prefix-icon">
              <SearchIcon />
            </el-icon>
          </template>
          <template v-slot:append>
            <el-button @click="handleSearch">
              <el-icon><SearchIcon /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>

      <div class="user-menu">
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            <el-icon><User /></el-icon>
            我的 <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="home">返回首页</el-dropdown-item>
              <el-dropdown-item command="logout" divided>登出</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-menu>

    <!-- 内容区域 -->
    <div class="content-container">
      <!-- 用户管理 -->
      <div v-if="activeIndex === '1'" class="section">
        <div class="section-title">
          <el-icon><User /></el-icon>
          <h2>用户管理中心</h2>
        </div>

        <!-- 工具栏 -->
        <div class="toolbar">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名或邮箱"
              style="width: 300px"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">搜索</el-button>
              </template>
            </el-input>
          </div>

          <div class="admin-box">
            <!-- 批量操作按钮 -->
            <el-dropdown v-if="selectedUsers.length > 0" @command="handleBatchCommand">
              <el-button type="primary">
                <el-icon><More /></el-icon>
                批量操作 <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="batchBan">
                    <el-icon><Lock /></el-icon>
                    批量封禁
                  </el-dropdown-item>
                  <el-dropdown-item command="batchUnban">
                    <el-icon><Unlock /></el-icon>
                    批量解封
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            
            <el-button type="primary" @click="refreshUsers">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
            <el-button type="info" @click="goBack">
              <el-icon><Back /></el-icon>
              返回首页
            </el-button>
          </div>
        </div>

        <!-- 用户表格 -->
        <el-table
          :data="paginatedUsers"
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          ref="userTable">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="userId" label="用户ID" width="80">
            <template #default="{ row }">
              <span>{{ row.userId }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="用户名" width="150">
            <template #default="{ row }">
              <span>{{ row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userEmail" label="邮箱" width="200">
            <template #default="{ row }">
              <span>{{ row.userEmail }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userRole" label="角色" width="100">
            <template #default="{ row }">
              <el-tag :type="getRoleType(row.userRole)">
                {{ getRoleText(row.userRole) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="userStatus" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.userStatus)">
                {{ getStatusText(row.userStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" fixed="right">
            <template #default="{ row }">
              <!-- 封禁/解封按钮 -->
              <el-button
                :type="row.userStatus === '0' ? 'danger' : 'success'"
                size="small"
                @click="toggleUserStatus(row)"
                :disabled="row.userId === currentUserId || row.userRole.toUpperCase() === 'ADMIN'">
                {{ row.userStatus === '0' ? '封禁' : '解封' }}
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="resetPassword(row)">
                重置密码
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="viewUserDetail(row)">
                详情
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteUser(row)"
                :disabled="row.userId === currentUserId || row.userRole.toUpperCase() === 'ADMIN'">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="filteredUsers.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 系统设置 -->
      <div v-if="activeIndex === '2'" class="section">
        <div class="section-title">
          <el-icon><Setting /></el-icon>
          <h2>系统设置</h2>
        </div>

        <div class="settings-content">
          <el-card class="setting-card">
            <template #header>
              <div class="card-header">
                <el-icon><User /></el-icon>
                <span>用户管理设置</span>
              </div>
            </template>
            <div class="setting-item">
              <span class="setting-label">默认用户角色：</span>
              <el-select v-model="defaultRole" placeholder="选择默认角色">
                <el-option label="普通用户" value="user"></el-option>
                <el-option label="管理员" value="admin"></el-option>
              </el-select>
            </div>
            <div class="setting-item">
              <span class="setting-label">密码重置长度：</span>
              <el-input-number v-model="passwordLength" :min="4" :max="12" />
            </div>
          </el-card>

          <el-card class="setting-card">
            <template #header>
              <div class="card-header">
                <el-icon><Lock /></el-icon>
                <span>安全设置</span>
              </div>
            </template>
            <div class="setting-item">
              <span class="setting-label">启用密码复杂度检查：</span>
              <el-switch v-model="passwordComplexity" />
            </div>
            <div class="setting-item">
              <span class="setting-label">会话超时时间（分钟）：</span>
              <el-input-number v-model="sessionTimeout" :min="5" :max="1440" />
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 重置密码对话框 -->
    <el-dialog
      title="重置密码"
      v-model="resetPasswordDialogVisible"
      width="500px"
      :close-on-click-modal="false">
      <div class="reset-password-content">
        <div class="user-info">
          <p><strong>用户ID：</strong>{{ selectedUser?.userId }}</p>
          <p><strong>用户名：</strong>{{ selectedUser?.userName }}</p>
          <p><strong>邮箱：</strong>{{ selectedUser?.userEmail }}</p>
        </div>

        <el-alert
          title="注意"
          type="warning"
          :closable="false"
          show-icon>
          <template #default>
            <p>重置后系统将生成新的随机密码，新密码将以明文形式显示在界面上。</p>
            <p>请确保用户及时修改密码。</p>
          </template>
        </el-alert>

        <div v-if="resetResult" class="reset-result">
          <el-alert
            :title="resetResult.message"
            :type="resetResult.success ? 'success' : 'error'"
            :closable="false"
            show-icon>
            <template #default>
              <div v-if="resetResult.success">
                <p><strong>新密码：</strong></p>
                <div class="new-password">
                  <el-input
                    v-model="resetResult.newPassword"
                    readonly
                    type="text"
                    class="password-display">
                    <template #append>
                      <el-button @click="copyPassword">
                        <el-icon><CopyDocument /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                </div>
                <p class="password-tip">请将此密码告知用户，建议用户登录后立即修改密码。</p>
              </div>
            </template>
          </el-alert>
        </div>
      </div>

      <template #footer>
        <el-button @click="resetPasswordDialogVisible = false">关闭</el-button>
        <el-button
          type="primary"
          @click="confirmResetPassword"
          :loading="resetting"
          :disabled="!!resetResult">
          {{ resetting ? '重置中...' : '确认重置' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
      title="用户详情"
      v-model="userDetailDialogVisible"
      width="600px">
      <div v-if="selectedUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">
            {{ selectedUser.userId }}
          </el-descriptions-item>
          <el-descriptions-item label="用户名">
            {{ selectedUser.userName }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ selectedUser.userEmail }}
          </el-descriptions-item>
          <el-descriptions-item label="角色">
            <el-tag :type="getRoleType(selectedUser.userRole)">
              {{ getRoleText(selectedUser.userRole) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedUser.userStatus)">
              {{ getStatusText(selectedUser.userStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">
            {{ formatDate(selectedUser.createTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="userDetailDialogVisible = false">关闭</el-button>
        <el-button type="warning" @click="resetPassword(selectedUser)">
          重置密码
        </el-button>
        <!-- 详情页也添加封禁/解封按钮 -->
        <el-button
          :type="selectedUser?.userStatus === '0' ? 'danger' : 'success'"
          @click="toggleUserStatus(selectedUser)"
          :disabled="!selectedUser || selectedUser.userId === currentUserId || selectedUser.userRole.toUpperCase() === 'ADMIN'">
          {{ selectedUser?.userStatus === '0' ? '封禁' : '解封' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Setting, Search as SearchIcon, ArrowDown, Refresh, Lock, CopyDocument, Back, More, Unlock } from '@element-plus/icons-vue'
import { getAllUsers, updateUserStatus } from '@/api/user'

export default {
  name: 'UserCenterView',
  components: {
    User,
    Setting,
    SearchIcon,
    ArrowDown,
    Refresh,
    Lock,
    CopyDocument,
    Back,
    More,
    Unlock
  },
  data() {
    return {
      activeIndex: '1',
      searchKeyword: '',
      users: [],
      filteredUsers: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      selectedUsers: [],
      selectedUser: null,

      // 重置密码相关
      resetPasswordDialogVisible: false,
      resetting: false,
      resetResult: null,

      // 用户详情
      userDetailDialogVisible: false,

      // 系统设置
      defaultRole: 'user',
      passwordLength: 6,
      passwordComplexity: true,
      sessionTimeout: 30,

      // 当前用户ID
      currentUserId: null
    }
  },
  computed: {
    paginatedUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredUsers.slice(start, end);
    }
  },
  mounted() {
    this.loadUsers()
    this.loadUserInfo()
    this.loadCurrentUserId()
  },
  methods: {
    handleSelect(key) {
      this.activeIndex = key
    },

    handleCommand(command) {
      if (command === 'home') {
        this.$router.push('/')
      } else if (command === 'logout') {
        this.logout()
      }
    },

    async loadUsers() {
      try {
        this.loading = true
        const response = await getAllUsers()
        if (response.data) {
          this.users = response.data || []
          this.applyFilters()
        } else {
          ElMessage.error('获取用户列表失败')
          this.users = []
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
        this.users = []
      } finally {
        this.loading = false
      }
    },

    async refreshUsers() {
      await this.loadUsers()
      ElMessage.success('数据刷新成功')
    },

    applyFilters() {
      let data = [...this.users]
      if (this.searchKeyword && this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        data = data.filter(user =>
          user && (
            (user.userName && user.userName.toLowerCase().includes(keyword)) ||
            (user.userEmail && user.userEmail.toLowerCase().includes(keyword))
          )
        )
      }
      this.filteredUsers = data
      this.currentPage = 1
    },

    handleSearch() {
      this.applyFilters()
    },

    handleSelectionChange(selection) {
      this.selectedUsers = selection
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
    },

    handleCurrentChange(val) {
      this.currentPage = val
    },

    resetPassword(user) {
      this.selectedUser = user
      this.resetResult = null
      this.resetPasswordDialogVisible = true
    },

    async confirmResetPassword() {
      try {
        this.resetting = true
        const randomPassword = this.generateRandomPassword(this.passwordLength)
        
        this.resetResult = {
          success: true,
          message: '密码重置成功（当前为模拟重置，需后端接口支持真实修改）',
          newPassword: randomPassword
        }
        ElMessage.success('模拟重置密码成功，新密码已生成')
      } catch (error) {
        console.error('重置密码异常:', error)
        this.resetResult = {
          success: false,
          message: '重置密码失败'
        }
        ElMessage.error('重置密码失败')
      } finally {
        this.resetting = false
      }
    },

    generateRandomPassword(length) {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      let password = ''
      for (let i = 0; i < length; i++) {
        password += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      return password
    },

    copyPassword() {
      if (this.resetResult && this.resetResult.newPassword) {
        navigator.clipboard.writeText(this.resetResult.newPassword).then(() => {
          ElMessage.success('密码已复制到剪贴板')
        }).catch(() => {
          ElMessage.error('复制失败，请手动复制')
        })
      }
    },

    viewUserDetail(user) {
      this.selectedUser = user
      this.userDetailDialogVisible = true
    },

    getRoleType(role) {
      const roleMap = {
        'ADMIN': 'danger',
        'USER': 'success'
      }
      return roleMap[role.toUpperCase()] || 'info'
    },

    getRoleText(role) {
      const roleMap = {
        'ADMIN': '管理员',
        'USER': '普通用户'
      }
      return roleMap[role.toUpperCase()] || '未知'
    },

    getStatusType(status) {
      const statusMap = {
        '0': 'success',
        '1': 'danger'
      }
      return statusMap[status] || 'info'
    },

    getStatusText(status) {
      const statusMap = {
        '0': '正常',
        '1': '禁用'
      }
      return statusMap[status] || '未知'
    },

    formatDate(dateString) {
      if (!dateString) return '-'
      try {
        const date = new Date(dateString)
        return date.toLocaleDateString('zh-CN')
      } catch {
        return dateString
      }
    },

    loadUserInfo() {
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        const user = JSON.parse(userInfo)
        if (user.userRole.toUpperCase() !== 'ADMIN') {
          ElMessage.error('权限不足，需要管理员权限')
          this.$router.push('/')
        }
      } else {
        ElMessage.error('请先登录')
        this.$router.push('/login')
      }
    },

    logout() {
      localStorage.removeItem('userInfo')
      localStorage.removeItem('token')
      this.$router.push('/login')
      ElMessage.success('注销成功')
    },

    loadCurrentUserId() {
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        const user = JSON.parse(userInfo)
        this.currentUserId = user.userId
      }
    },

    async deleteUser(user) {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 "${user.userName}" 吗？此操作不可撤销！`,
          '删除确认',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'el-button--danger'
          }
        )
        ElMessage.warning('当前系统暂不支持用户删除功能')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除操作异常:', error)
          ElMessage.error('删除操作异常')
        }
      }
    },

    goBack() {
      this.$router.push('/')
    },

    // 新增：切换用户状态（封禁/解封）
    async toggleUserStatus(user) {
      try {
        // 确认操作
        const isBan = user.userStatus === '0'
        const confirmMessage = isBan 
          ? `确定要封禁用户 "${user.userName}" 吗？封禁后用户将无法登录系统。`
          : `确定要解封用户 "${user.userName}" 吗？解封后用户可以正常登录系统。`
        
        await ElMessageBox.confirm(
          confirmMessage,
          isBan ? '封禁确认' : '解封确认',
          {
            confirmButtonText: isBan ? '确定封禁' : '确定解封',
            cancelButtonText: '取消',
            type: isBan ? 'warning' : 'success'
          }
        )

        // 调用后端接口更新状态
        const newStatus = isBan ? '1' : '0'
        const response = await updateUserStatus({
          userId: user.userId,
          userStatus: newStatus
        })

        if (response.success) {
          // 更新本地数据
          const index = this.users.findIndex(u => u.userId === user.userId)
          if (index !== -1) {
            this.users[index].userStatus = newStatus
            this.applyFilters() // 重新应用筛选
          }
          
          ElMessage.success(isBan ? '用户封禁成功' : '用户解封成功')
          
          // 如果是在详情页，更新详情页数据
          if (this.userDetailDialogVisible && this.selectedUser && this.selectedUser.userId === user.userId) {
            this.selectedUser.userStatus = newStatus
          }
        } else {
          ElMessage.error(response.message || (isBan ? '用户封禁失败' : '用户解封失败'))
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('更新用户状态异常:', error)
          ElMessage.error('操作异常，请稍后重试')
        }
      }
    },

    // 新增：处理批量操作命令
    async handleBatchCommand(command) {
      try {
        if (this.selectedUsers.length === 0) {
          ElMessage.warning('请先选择用户')
          return
        }

        // 检查是否包含管理员管理员
        const hasAdmin = this.selectedUsers.some(user => user.userRole.toUpperCase() === 'ADMIN')
        if (hasAdmin) {
          ElMessage.error('不能对管理员执行此操作')
          return
        }

        // 检查是否包含当前用户
        const hasCurrentUser = this.selectedUsers.some(user => user.userId === this.currentUserId)
        if (hasCurrentUser) {
          ElMessage.error('不能对当前登录用户执行此操作')
          return
        }

        let confirmMessage = ''
        let newStatus = ''
        
        if (command === 'batchBan') {
          // 过滤掉已经封禁的用户
          const usersToBan = this.selectedUsers.filter(user => user.userStatus === '0')
          if (usersToBan.length === 0) {
            ElMessage.warning('所选用户中没有可封禁的用户')
            return
          }
          
          confirmMessage = `确定要批量封禁 ${usersToBan.length} 个用户吗？封禁后用户将无法登录系统。`
          newStatus = '1'
        } else if (command === 'batchUnban') {
          // 过滤掉已经解封的用户
          const usersToUnban = this.selectedUsers.filter(user => user.userStatus === '1')
          if (usersToUnban.length === 0) {
            ElMessage.warning('所选用户中没有可解封的用户')
            return
          }
          
          confirmMessage = `确定要批量解封 ${usersToUnban.length} 个用户吗？解封后用户可以正常登录系统。`
          newStatus = '0'
        }

        await ElMessageBox.confirm(
          confirmMessage,
          command === 'batchBan' ? '批量封禁确认' : '批量解封确认',
          {
            confirmButtonText: '确定执行',
            cancelButtonText: '取消',
            type: command === 'batchBan' ? 'warning' : 'success'
          }
        )

        // 批量更新用户状态
        let successCount = 0
        let failCount = 0

        for (const user of this.selectedUsers) {
          // 只处理需要变更状态的用户
          if (user.userStatus !== newStatus) {
            try {
              const response = await updateUserStatus({
                userId: user.userId,
                userStatus: newStatus
              })
              
              if (response.success) {
                successCount++
                // 更新本地数据
                const index = this.users.findIndex(u => u.userId === user.userId)
                if (index !== -1) {
                  this.users[index].userStatus = newStatus
                }
              } else {
                failCount++
              }
            } catch (error) {
              console.error(`更新用户 ${user.userName} 状态失败:`, error)
              failCount++
            }
          }
        }

        // 重新应用筛选
        this.applyFilters()
        
        // 显示结果
        if (successCount > 0) {
          ElMessage.success(`${command === 'batchBan' ? '批量封禁' : '批量解封'}成功，共处理 ${successCount} 个用户`)
        }
        if (failCount > 0) {
          ElMessage.error(`有 ${failCount} 个用户处理失败`)
        }
        
        // 清空选择
        this.$refs.userTable.clearSelection()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量操作异常:', error)
          ElMessage.error('批量操作异常，请稍后重试')
        }
      }
    },
    async handleBatchCommand(command) {
      try {
        if (this.selectedUsers.length === 0) {
          ElMessage.warning('请先选择用户')
          return
        }

        // 检查是否包含管理员
        const hasAdmin = this.selectedUsers.some(user => user.userRole.toUpperCase() === 'ADMIN')
        if (hasAdmin) {
          ElMessage.error('不能对管理员执行此操作')
          return
        }

        // 检查是否包含当前用户
        const hasCurrentUser = this.selectedUsers.some(user => user.userId === this.currentUserId)
        if (hasCurrentUser) {
          ElMessage.error('不能对当前登录用户执行此操作')
          return
        }

        let confirmMessage = ''
        let newStatus = ''
        
        if (command === 'batchBan') {
          // 过滤掉已经封禁的用户
          const usersToBan = this.selectedUsers.filter(user => user.userStatus === '0')
          if (usersToBan.length === 0) {
            ElMessage.warning('所选用户中没有可封禁的用户')
            return
          }
          
          confirmMessage = `确定要批量封禁 ${usersToBan.length} 个用户吗？封禁后用户将无法登录系统。`
          newStatus = '1'
        } else if (command === 'batchUnban') {
          // 过滤掉已经解封的用户
          const usersToUnban = this.selectedUsers.filter(user => user.userStatus === '1')
          if (usersToUnban.length === 0) {
            ElMessage.warning('所选用户中没有可解封的用户')
            return
          }
          
          confirmMessage = `确定要批量解封 ${usersToUnban.length} 个用户吗？解封后用户可以正常登录系统。`
          newStatus = '0'
        }

        await ElMessageBox.confirm(
          confirmMessage,
          command === 'batchBan' ? '批量封禁确认' : '批量解封确认',
          {
            confirmButtonText: '确定执行',
            cancelButtonText: '取消',
            type: command === 'batchBan' ? 'warning' : 'success'
          }
        )

        // 批量更新用户状态
        // 这里可以优化为批量接口调用，目前先循环调用单个接口
        let successCount = 0
        let failCount = 0

        for (const user of this.selectedUsers) {
          // 只处理需要变更状态的用户
          if (user.userStatus !== newStatus) {
            try {
              const response = await updateUserStatus({
                userId: user.userId,
                userStatus: newStatus
              })
              
              if (response.success) {
                successCount++
                // 更新本地数据
                const index = this.users.findIndex(u => u.userId === user.userId)
                if (index !== -1) {
                  this.users[index].userStatus = newStatus
                }
              } else {
                failCount++
              }
            } catch (error) {
              console.error(`更新用户 ${user.userName} 状态失败:`, error)
              failCount++
            }
          }
        }

        // 重新应用筛选
        this.applyFilters()
        
        // 显示结果
        if (successCount > 0) {
          ElMessage.success(`${command === 'batchBan' ? '批量封禁' : '批量解封'}成功，共处理 ${successCount} 个用户`)
        }
        if (failCount > 0) {
          ElMessage.error(`有 ${failCount} 个用户处理失败`)
        }
        
        // 清空选择
        this.$refs.userTable.clearSelection()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量操作异常:', error)
          ElMessage.error('批量操作异常，请稍后重试')
        }
      }
    }
  }
}
</script>

<style scoped>
/* 样式部分完全不变，和你提供的原始代码一致 */
.user-center {
  min-height: 100vh;
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  background-attachment: fixed;
  overflow: hidden;
}

* {
  scrollbar-width: none;
  -ms-overflow-style: none;
}

*::-webkit-scrollbar {
  display: none;
}

body {
  overflow: hidden !important;
}

.nav-menu {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.nav-search {
  position: absolute;
  right: 200px;
  top: 50%;
  transform: translateY(-50%);
}

.nav-search-input {
  width: 280px;
}

.nav-search-input .el-input__wrapper {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(168, 237, 234, 0.4);
  border-radius: 25px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.nav-search-input .el-input__wrapper:hover {
  border-color: #a8edea;
  box-shadow: 0 4px 15px rgba(168, 237, 234, 0.3);
}

.nav-search-input .el-input__wrapper.is-focus {
  border-color: #a8edea;
  box-shadow: 0 4px 15px rgba(168, 237, 234, 0.4);
}

.nav-search-input .el-button .el-icon {
  background: linear-gradient(135deg, #a8edea, #fed6e3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: all 0.3s ease;
}

.nav-search-input .el-button:hover .el-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.search-prefix-icon {
  background: linear-gradient(135deg, #a8edea, #fed6e3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: all 0.3s ease;
  font-size: 16px;
}

.nav-search-input .el-input__wrapper:hover .search-prefix-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.nav-search-input .el-input__wrapper.is-focus .search-prefix-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.user-menu {
  position: absolute;
  right: 30px;
  top: 50%;
  transform: translateY(-50%);
}

.el-dropdown-link {
  color: #2c3e50;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 16px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  border: 1px solid rgba(102, 126, 234, 0.2);
}

.el-dropdown-link:hover {
  background: rgba(102, 126, 234, 0.1);
  border-color: #667eea;
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.el-dropdown-link .el-icon {
  font-size: 16px;
  background: linear-gradient(135deg, #a8edea, #fed6e3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: all 0.3s ease;
}

.el-dropdown-link:hover .el-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.nav-menu .el-menu-item .el-icon {
  margin-right: 8px;
  font-size: 18px;
  background: linear-gradient(135deg, #a8edea, #fed6e3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: all 0.3s ease;
}

.nav-menu .el-menu-item:hover .el-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.nav-menu .el-menu-item:hover {
  background-color: #e8e8e8 !important;
}

.nav-menu .el-menu-item.is-active {
  background-color: transparent !important;
}

.nav-menu .el-menu-item.is-active .el-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.content-container {
  padding: 20px;
  margin-top: 80px;
  overflow-y: auto;
  height: calc(100vh - 80px);
}

.section {
  background: rgba(255, 255, 255, 0.95);
  padding: 30px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin-bottom: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px 0;
  position: relative;
  overflow: hidden;
}

.section-title::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  border-radius: 2px;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.section-title::after {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.1), transparent);
  animation: shimmer 3s infinite;
}

@keyframes shimmer {
  0% { left: -100%; }
  100% { left: 100%; }
}

.section-title .el-icon {
  font-size: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-right: 20px;
  padding: 8px;
  border-radius: 12px;
  background-color: rgba(102, 126, 234, 0.1);
  transition: all 0.3s ease;
  position: relative;
  z-index: 2;
}

.section-title h2 {
  margin: 0;
  background: linear-gradient(135deg, #2c3e50 0%, #667eea 50%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-size: 32px;
  font-weight: 800;
  letter-spacing: 1px;
  position: relative;
  z-index: 2;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-box {
  display: flex;
  align-items: center;
}

.admin-box {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.reset-password-content {
  padding: 20px 0;
}

.user-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.user-info p {
  margin: 8px 0;
  color: #333;
}

.reset-result {
  margin-top: 20px;
}

.new-password {
  margin: 10px 0;
}

.password-display {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  font-size: 16px;
}

.password-tip {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

.user-detail {
  padding: 20px 0;
}

.settings-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.setting-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: bold;
  color: #333;
}

.card-header .el-icon {
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.setting-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.setting-label {
  font-weight: 500;
  color: #333;
  min-width: 150px;
}

@media (max-width: 1200px) {
  .nav-search {
    right: 180px;
  }
  .nav-search-input {
    width: 250px;
  }
}

@media (max-width: 992px) {
  .nav-search {
    right: 160px;
  }
  .nav-search-input {
    width: 220px;
  }
  .user-menu {
    right: 20px;
  }
}

@media (max-width: 768px) {
  .nav-search {
    position: static;
    transform: none;
    margin: 10px 20px;
    width: calc(100% - 40px);
  }
  .nav-search-input {
    width: 100%;
  }
  .user-menu {
    position: static;
    transform: none;
    margin: 10px 20px;
    text-align: center;
  }
  .nav-menu {
    flex-direction: column;
    height: auto;
  }
  .nav-menu .el-menu-item {
    width: 100%;
    text-align: center;
  }
  .settings-content {
    grid-template-columns: 1fr;
  }
  .toolbar {
    flex-direction: column;
    gap: 15px;
  }
  .admin-box {
    justify-content: center;
  }
}
</style>
